#!/bin/python3
"""Install RoboRio toolchain for Windows and Linux."""
import os
import shutil
import tarfile
import zipfile
import platform
import requests

year = "2022"
release = "1"
toolchain_version = "7.3.0"

if platform.system() == "Windows":
    file = "FRC-{}-{}64-Toolchain-{}.zip".format(year, platform.system(), toolchain_version)
else:
    file = "FRC-{}-{}-Toolchain-{}.tar.gz".format(year, platform.system(), toolchain_version)

print("*******************************************")
print("* Installing RoboRIO cross compiler tools *")
print("*******************************************")

if os.path.exists(os.path.expanduser("~") + "/FRCppTemp"):
    shutil.rmtree(os.path.expanduser("~") + "/FRCppTemp")
os.makedirs(os.path.expanduser("~") + "/FRCppTemp")
os.chdir(os.path.expanduser("~") + "/FRCppTemp")

download = requests.get(
        "https://github.com/wpilibsuite/roborio-toolchain/releases/download/v{}-{}/{}".format(year, release, file)
)
with open(file, "wb") as f:
    f.write(download.content)

if file.endswith("zip"):
    with zipfile.ZipFile(file) as z:
        z.extractall()
        z.close()
else:
    with tarfile.open(file, "r:gz") as tar:
        tar.extractall()
        tar.close()

directories = [
    "frc{}/roborio/bin/".format(year), # Handle aliases for cross compiling
    "frc{}/roborio/lib/".format(year), # Same as bin but for libs
    "frc{}/roborio/share/".format(year), # Contains man files
    "frc{}/roborio/include/".format(year), # Contains misc include files
    "frc{}/roborio/libexec/".format(year), # https://unix.stackexchange.com/questions/312146/what-is-the-purpose-of-usr-libexec
    "frc{}/roborio/arm-frc{}-linux-gnueabi".format(year, year) # Contains the actual compilers and libs
]

if platform.system() == "Windows":
    print('')
else:
    for file in os.listdir(directories[0]):
        shutil.copy(os.path.join(directories[0], file), "/usr/local/bin")
    for file in os.listdir(directories[1]):
        shutil.copy(os.path.join(directories[1], file), "/lib")
    for file in os.listdir(directories[2]):
        shutil.copy(os.path.join(directories[2], file), "/usr/share")
    for file in os.listdir(directories[3]):
        shutil.copy(os.path.join(directories[3], file), "/include")
    for file in os.listdir(directories[4]):
        shutil.copy(os.path.join(directories[4], file), "/usr/libexec")
    shutil.copytree(directories[5], "/usr")

os.chdir(os.path.expanduser("~"))
shutil.rmtree(os.path.expanduser("~") + "/FRCppTemp")
